<!DOCTYPE html><html lang="zh-Hans"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="iOS内存泄漏"><meta name="keywords" content=""><meta name="author" content="kyren"><meta name="copyright" content="kyren"><title>iOS内存泄漏 | Kyren's Blog</title><link rel="shortcut icon" href="/melody-favicon.ico"><link rel="stylesheet" href="/css/index.css?version=1.9.0"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.9.0"><meta name="format-detection" content="telephone=no"><meta http-equiv="x-dns-prefetch-control" content="on"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="dns-prefetch" href="https://hm.baidu.com"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?cf87fcdbd9ab7cf93d894f7c219ae78f";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();</script><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><script src="https://v1.hitokoto.cn/?encode=js&amp;charset=utf-8&amp;select=.footer_custom_text" defer></script><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容:${query}"}},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  hexoVersion: '6.2.0'
} </script><meta name="generator" content="Hexo 6.2.0"></head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar" data-display="true"><div class="toggle-sidebar-info text-center"><span data-toggle="切换文章详情">切换站点概览</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">目录</div><div class="sidebar-toc__progress"><span class="progress-notice">你已经读了</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-4"><a class="toc-link" href="#Instrument-%E2%80%94-Leaks%EF%BC%8CAllocations%EF%BC%8CAnalyze"><span class="toc-number">1.</span> <span class="toc-text">Instrument — Leaks，Allocations，Analyze</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%AC%AC%E4%B8%89%E6%96%B9%E5%B7%A5%E5%85%B7"><span class="toc-number">2.</span> <span class="toc-text">第三方工具</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%80%E3%80%81MLeaksFinder"><span class="toc-number">3.</span> <span class="toc-text">一、MLeaksFinder</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BA%8C%E3%80%81PLeakSniffer"><span class="toc-number">4.</span> <span class="toc-text">二、PLeakSniffer</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%89%E3%80%81%E4%BD%BF%E7%94%A8Facebook%E5%BC%80%E6%BA%90%E6%A3%80%E6%9F%A5%E5%B7%A5%E5%85%B7FBRetainCycleDetector"><span class="toc-number">5.</span> <span class="toc-text">三、使用Facebook开源检查工具FBRetainCycleDetector</span></a></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="https://avatars.githubusercontent.com/u/5827823?v=4"></div><div class="author-info__name text-center">kyren</div><div class="author-info__description text-center">huluo的技术博客</div><div class="follow-button"><a target="_blank" rel="noopener" href="https://github.com/huluo666">Follow Me</a></div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">文章</span><span class="pull-right">239</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">标签</span><span class="pull-right">41</span></a><a class="author-info-articles__categories article-meta" href="/categories"><span class="pull-left">分类</span><span class="pull-right">29</span></a></div><hr><div class="author-info-links"><div class="author-info-links__title text-center">Links</div><a class="author-info-links__name text-center" target="_blank" rel="noopener" href="http://192.168.2.212:9090/">Jira</a><a class="author-info-links__name text-center" target="_blank" rel="noopener" href="http://192.168.2.212:8090/">Confluence</a><a class="author-info-links__name text-center" target="_blank" rel="noopener" href="http://bloc.leniugame.com/">Leniu</a></div></div></div><div id="content-outer"><div class="no-bg" id="top-container"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">Kyren's Blog</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus">   <a class="site-page" href="/">主页</a><a class="site-page" href="/essay">随笔</a><a class="site-page" href="/archives">归档</a><a class="site-page" href="/tags">标签</a><a class="site-page" href="/categories">分类</a><a class="site-page" href="/about">关于</a></span><span class="pull-right"><a class="site-page social-icon search"><i class="fa fa-search"></i><span> 搜索</span></a></span></div><div id="post-info"><div id="post-title">iOS内存泄漏</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2018-03-27</time></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><h4 id="Instrument-—-Leaks，Allocations，Analyze"><a href="#Instrument-—-Leaks，Allocations，Analyze" class="headerlink" title="Instrument — Leaks，Allocations，Analyze"></a>Instrument — Leaks，Allocations，Analyze</h4><p><strong>Analyze</strong>-静态分析工具</p>
<p>Product-&gt;Analyze(<code>command+shift+B</code>)</p>
<p>可以找出代码潜在错误,如内存泄露,未使用函数和变量等,还可以检测出一些内存泄漏问题，比如一些比较明显的循环引用，CF库对象未release等相对简单的问题，通常是在进行其他方式检测之前就使用的方式，把一些简单的问题先发现并处理了。</p>
<p>主要分析以下四种问题</p>
<ul>
<li>逻辑错误：访问空指针或为初始化的变量等；</li>
<li>内存管理错误：如内存泄漏等；</li>
<li>声明错误：从未使用过的变量</li>
<li>Api调用错误：未包含使用库和框架</li>
</ul>
<p> Allocations工具是一个跟踪由应用程序分配的对象内存的工具。可以用来在疑似内存泄露的地方，通过反复操作，查看某些对象内存是否有被正常的释放，从而得知是否发生内存泄露。</p>
<p><strong>Instruments</strong>-动态分析工具（product -&gt; profile）</p>
<p>内存泄漏检测工具-Leaks</p>
<p>Instruments工具(<code>command+I</code>)-选择Leaks选项</p>
<p>选择Target，在右下角Display Setting面板的Call Tree，勾选Invert Call Tree和Hide System Libraries，方便接下来我们迅速查找有内存问题的代码段。</p>
<h4 id="第三方工具"><a href="#第三方工具" class="headerlink" title="第三方工具"></a>第三方工具</h4><p>相对于系统工具，方便快速多了</p>
<h4 id="一、MLeaksFinder"><a href="#一、MLeaksFinder" class="headerlink" title="一、MLeaksFinder"></a>一、MLeaksFinder</h4><p>精准 iOS 内存泄露检测工具</p>
<p><a target="_blank" rel="noopener" href="https://github.com/Tencent/MLeaksFinder">https://github.com/Tencent/MLeaksFinder</a></p>
<p>直接拖入<code>MLeaksFinder</code>文件夹到工程即可</p>
<p><strong>MLeaksFinder 新特性</strong> <a target="_blank" rel="noopener" href="https://wereadteam.github.io/2016/07/20/MLeaksFinder2/">https://wereadteam.github.io/2016/07/20/MLeaksFinder2/</a></p>
<p>MLeaksFinder的原理：</p>
<p>使用runtime方法交换，它swizzle了NavigationController的Push和Pop相关方法来管理viewController和view的生命周期, 在你Pop掉viewController的时候, 会执行这么一段代码</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">__weak id weakSelf = self;</span><br><span class="line">    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^&#123;</span><br><span class="line">        [weakSelf assertNotDealloc];</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>3秒后执行 [weakSelf assertNotDealloc]; 如果这个时候view和viewController已经释放了, 那么weakSelf应该为nil, 所以将不会触发断言, 否则将会打印日志, 触发断言.</p>
<p>MLeaksFinder的原理还是很简单的, 它swizzle了NavigationController的Push和Pop相关方法来管理viewController和view的生命周期, 在你Pop掉viewController的时候, 会执行这么一段代码</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">__weak id weakSelf = self;</span><br><span class="line">    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^&#123;</span><br><span class="line">        [weakSelf assertNotDealloc];</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>3秒后执行 [weakSelf assertNotDealloc]; 如果这个时候view和viewController已经释放了, 那么weakSelf应该为nil, 所以将不会触发断言, 否则将会打印日志, 触发断言.</p>
<p><strong>OOMDetector</strong></p>
<p><a target="_blank" rel="noopener" href="https://github.com/Tencent/OOMDetector">https://github.com/Tencent/OOMDetector</a></p>
<p>同样来自腾讯，OOMDetector是一个iOS内存监控组件，应用此组件可以帮助你轻松实现OOM监控、大内存分配监控、内存泄漏检测等功能。</p>
<p><a target="_blank" rel="noopener" href="https://juejin.im/post/5a58f1a76fb9a01cab283392">【腾讯开源】iOS爆内存问题解决方案-OOMDetector组件</a></p>
<h4 id="二、PLeakSniffer"><a href="#二、PLeakSniffer" class="headerlink" title="二、PLeakSniffer"></a>二、PLeakSniffer</h4><p>iOS内存泄漏自动检测工具</p>
<p><a target="_blank" rel="noopener" href="https://github.com/music4kid/PLeakSniffer">https://github.com/music4kid/PLeakSniffer</a></p>
<p><a target="_blank" rel="noopener" href="http://mrpeak.cn/blog/leak/">http://mrpeak.cn/blog/leak/</a></p>
<p>在<code>AppDelegate.m</code>加入</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">if</span> DEBUG</span></span><br><span class="line">[[PLeakSniffer sharedInstance] installLeakSniffer];</span><br><span class="line">[[PLeakSniffer sharedInstance] addIgnoreList:@[<span class="string">@&quot;MySingletonController&quot;</span>]];<span class="comment">//需要忽略的文件</span></span><br><span class="line">[[PLeakSniffer sharedInstance]  alertLeaks];<span class="comment">//使用弹出框提示</span></span><br><span class="line"><span class="meta">#<span class="keyword">endif</span></span></span><br></pre></td></tr></table></figure>

<h4 id="三、使用Facebook开源检查工具FBRetainCycleDetector"><a href="#三、使用Facebook开源检查工具FBRetainCycleDetector" class="headerlink" title="三、使用Facebook开源检查工具FBRetainCycleDetector"></a>三、使用Facebook开源检查工具FBRetainCycleDetector</h4><p>使用的是MRC机制的文件，需要设置对应文件的Compiler Flags为<code>-fno-objc-arc</code>。</p>
<p>如何使用，使用<code>FBRetainCycleDetector</code>，需要将以上4个文件改成<code>-fno-objc-arc</code></p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">FBBlockStrongLayout</span><br><span class="line">FBAssociationManager</span><br><span class="line">FBBlockStrongRelationDetector</span><br><span class="line">FBClassStrongLayoutHelpers</span><br></pre></td></tr></table></figure>











</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">kyren</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://huluo666.gitee.io/2018/03/27/iOS内存泄漏/">http://huluo666.gitee.io/2018/03/27/iOS内存泄漏/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://huluo666.gitee.io">Kyren's Blog</a>！</span></div></div><div class="post-meta__tag-list"></div><nav id="pagination"><div class="prev-post pull-left"><a href="/2018/03/29/%E4%BC%98%E9%9B%85%E7%9A%84%E4%BD%BF%E7%94%A8Sublime-Text3/"><i class="fa fa-chevron-left">  </i><span>优雅的使用Sublime-Text3</span></a></div><div class="next-post pull-right"><a href="/2018/03/27/iOS%E5%B8%B8%E7%94%A8%E7%AC%AC%E4%B8%89%E5%88%86%E5%BA%93%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/"><span>iOS常用第三分库源码分析</span><i class="fa fa-chevron-right"></i></a></div></nav></div></div><footer><div class="layout" id="footer"><div class="copyright">&copy;2022 By kyren</div><div class="framework-info"><span>驱动 - </span><a target="_blank" rel="noopener" href="http://hexo.io"><span>Hexo</span></a><span class="footer-separator">|</span><span>主题 - </span><a target="_blank" rel="noopener" href="https://github.com/Molunerfinn/hexo-theme-melody"><span>Melody</span></a></div><div class="footer_custom_text">hitokoto</div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv"><i class="fa fa-file"></i><span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/lib/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.9.0"></script><script src="/js/fancybox.js?version=1.9.0"></script><script src="/js/sidebar.js?version=1.9.0"></script><script src="/js/copy.js?version=1.9.0"></script><script src="/js/fireworks.js?version=1.9.0"></script><script src="/js/transition.js?version=1.9.0"></script><script src="/js/scroll.js?version=1.9.0"></script><script src="/js/head.js?version=1.9.0"></script><script src="/js/search/local-search.js"></script><script>if(/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
  $('#top-container').addClass('is-mobile')
}</script><div class="search-dialog" id="local-search"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章"></div></div></div><hr><div id="local-search-results"><div id="local-hits"></div><div id="local-stats"><div class="local-search-stats__hr" id="hr"><span>由</span> <a target="_blank" rel="noopener" href="https://github.com/wzpan/hexo-generator-search" style="color:#49B1F5;">hexo-generator-search</a>
 <span>提供支持</span></div></div></div><span class="search-close-button"><i class="fa fa-times"></i></span></div><div class="search-mask"></div></body></html>